package com.cn.designpatterns.ex.concrete.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author zhangyi
 * @date 2018/12/25 16:49
 */
public class CglibProxyMethod implements MethodInterceptor {

    Object target;

    public CglibProxyMethod(Object target) {
        this.target = target;
    }

    public Object getInstance(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        Object o = enhancer.create();
        return o;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib 使用方法拦截前...");
        Object invoke = methodProxy.invoke(target, objects);
        System.out.println("cglib 使用方法拦截后...");
        return invoke;
    }
}
